package packed

import (
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/sony/sonyflake"
	"time"
)

var (
	Sonyflake     *sonyflake.Sonyflake // 雪花算法实例
	SonyMachineID uint16               // 机器码
)

func init() {
	SnoyInit()
}
func GetMachineID() (uint16, error) { // 返回全局定义的机器码ID
	return SonyMachineID, nil
}

// 传入机器码ID，配置雪花算法机器码，起始时间。这里应该在项目初始化时调用。
func SnoyInit() (err error) {
	var ctx = gctx.New()
	med, _ := g.Cfg().Get(ctx, "machinecode") // 读取配置中的机器码
	SonyMachineID = med.Uint16()
	t, _ := time.Parse("2020-11-24", "2023-11-24")
	setting := sonyflake.Settings{StartTime: t, MachineID: GetMachineID}
	Sonyflake = sonyflake.NewSonyflake(setting)
	return
}

// 获取雪花算法ID
func GetID() (id uint64, err error) {
	if Sonyflake == nil {
		err = fmt.Errorf("出错啦")
		return
	}
	id, err = Sonyflake.NextID()
	return
}
